package com.fary.chapter01_aqs.ext_cyclicBarrier;

import com.fary.chapter01_aqs.ext_condition.FaryCondition;
import com.fary.chapter01_aqs.ext_reentrantLock.FaryReentrantLock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FaryCyclicBarrier {

    // 同步操作锁
    private final FaryReentrantLock lock = new FaryReentrantLock();
    // 线程拦截器
    private final FaryCondition trip = lock.newCondition();
    // 表示栅栏的当前代
    private FaryGeneration generation = new FaryGeneration();
    // 每次拦截的线程数
    private final int parties;
    // 换代前执行的任务
    private final Runnable barrierCommand;
    // 计数器
    private int count;

    public FaryCyclicBarrier(int parties) {
        this(parties, null);
    }

    public FaryCyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }

    /**
     * 非定时等待
     */
    public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }

    public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }

    private int dowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException {
        final FaryReentrantLock lock = this.lock;
        lock.lock();
        try {
            final FaryGeneration g = generation;
            // 检查当前栅栏是否被打翻
            if (g.broken)
                throw new BrokenBarrierException();
            // 检查当前线程是否被中断
            if (Thread.interrupted()) {
                // 如果当前线程被中断会做以下三件事
                // 1.打翻当前栅栏
                // 2.唤醒拦截的所有线程
                // 3.抛出中断异常
                breakBarrier();
                throw new InterruptedException();
            }
            // 每次都将计数器的值减1
            int index = --count;
            // 计数器的值减为0则需唤醒所有线程并转换到下一代
            if (index == 0) {  // tripped
                boolean ranAction = false;
                try {
                    // 唤醒所有线程前先执行指定的任务
                    final Runnable command = barrierCommand;
                    if (command != null)
                        command.run();
                    ranAction = true;
                    // 唤醒所有线程并转到下一代
                    nextGeneration();
                    return 0;
                } finally {
                    // 确保在任务未成功执行时能将所有线程唤醒
                    if (!ranAction)
                        breakBarrier();
                }
            }
            // 如果计数器不为0则执行此循环
            for (;;) {
                try {
                    // 根据传入的参数来决定是定时等待还是非定时等待
                    if (!timed)
                        trip.await();
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    // 若当前线程在等待期间被中断则打翻栅栏唤醒其他线程
                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {
                        // 若在捕获中断异常前已经完成在栅栏上的等待, 则直接调用中断操作
                        Thread.currentThread().interrupt();
                    }
                }
                // 如果线程因为打翻栅栏操作而被唤醒则抛出异常
                if (g.broken)
                    throw new BrokenBarrierException();
                // 如果线程因为换代操作而被唤醒则返回计数器的值
                if (g != generation)
                    return index;
                // 如果线程因为时间到了而被唤醒则打翻栅栏并抛出异常
                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }

    private void breakBarrier() {
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }

    private void nextGeneration() {
        trip.signalAll();
        count = parties;
        generation = new FaryGeneration();
    }



    private static class FaryGeneration {
        boolean broken = false;
    }
}
